<?php
/**
 *	css系统平台接口
 *  @author lyx
 */
namespace api\common\Css;
class Css
{
    //css正式系统调用地址：http://221.215.1.170:8086/HXCSSIC/WxHttpAction.action?method=getVipInfoByVipNo
    // const API_URL_PREFIX = 'http://103.94.200.164:8081/HXCSSIC/WxHttpAction.action';//api服务器地址
    const API_URL_PREFIX = 'http://221.215.1.170:8086/HXCSSIC/WxHttpAction.action';//api服务器地址

    const DEVICE_GET_URL = '?method=getVipInfoByVipNo&';//获取设备（报修）

    const BRAND_ID = 'HT';//品牌ID标识

    private $mobile;//当前手机号
    private $c_mobile;//历史手机号

    public  $debug =  false;
    public  $errMsg = "系统繁忙";
    private $_logcallback;

    /*
     * css系统返回的状态码=>状态码文字说明
     */
    public $error_arr = [
        0 => '数据为空',
        1 => '成功',
        2 => '非法操作，验证失败！',
        3 => '非法操作，手机号与工单不匹配！',
     ];

  


    /**
     * 获取金卡信息
     * @param $vip_no 金卡号
     */
    public function getDevice($vip_no){

        $data['telephone'] = $vip_no;
        $data['brand_id'] = self::BRAND_ID;
        $query_param = $this->getQueryParamStr($data);
        $result = $this->http_get(self::API_URL_PREFIX.self::DEVICE_GET_URL . $query_param);

        return $this->getRes($result);

    }

 
    /*
     * 获取最终结果
     * @param mixed $result 接口返回的结果
     * @param $is_list boolean 是否为多条数据
     * @param string $error_msg 自定义错误提示语
     * return boolean|array  boolean:固定值为false，表示非法请求或数据为空|array：结果集
     */
    public function getRes($result,$is_list = false,$error_msg = ''){
        if ($result){
            $json = json_decode($result,true);
            return $json;
        }

        return false;
    }


    public function getResByPost($result,$error_msg = ''){
        if ($result){
            $json = json_decode($result,true);
            if (!$json || $json['flag'] !== 1) {
                M('Test')->add(['msg' => 'post_error-' . date('Y-m-d H:i:s') . $result]);
                $this->errMsg = $error_msg ?: $this->error_arr[$json['flag']];
                return false;
            }

            return true;
        }
        return false;
    }

    /*
     * 拼接签名和当前时间，生成请求参数
     * @param array $query_param 请求参数数组
     * return array|string  $data|$query_param_str  formData数据|请求参数字符串
     */
    private function getQueryParamStr($data,$method = 'get'){
        if(!is_array($data)) return false;
        $data['time'] = strtotime(date('Ymd H:i:s'));
        $data['sign'] = $this->cssEncrypt($data);
        switch ($method){
            case 'post' ://如果是post提交方式，在formData内增加两个参数，'time'和'sign'
                return $data;
                break;
            default://默认get提交
                $query_param_str =  http_build_query($data);
                break;
        }
        return $query_param_str;
    }

    /*
     * 签名加密方法
     * @param array $query_param 请求参数数组
     * return string $sign 返回加密后的签名
     */
    private function cssEncrypt($query_param){
        ksort($query_param);
        //加入sign_key
        $tmp_sign = md5(implode($query_param) . md5('_/.(2;l@tx~XvF)`4aZC:f+Q1h<b*&pN%dms#g=q!@#$%^'));
        return substr($tmp_sign,0,24);
    }


    private function log($log){
        if ($this->debug ) {
            if (function_exists($this->_logcallback)) {
                if (is_array($log)) $log = print_r($log,true);
                return call_user_func($this->_logcallback,$log);
            }elseif (class_exists('Log')) {
                Log::write('CSS：'.$log, Log::DEBUG);
            }
        }
        return false;
    }

    /**
     * 生成随机字串
     * @param number $length 长度，默认为16，最长为32字节
     * @return string
     */
    public function generateNonceStr($length=16){
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for($i = 0; $i < $length; $i++)
        {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }


    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url){
        $oCurl = curl_init();

        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);

        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        $this_header = array(//传参设置中文编码，防止乱码
            "content-type: application/x-www-form-urlencoded;charset=UTF-8"
        );
        curl_setopt($oCurl,CURLOPT_HTTPHEADER,$this_header);
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
//                //上文已经使用header设置编码防止中文乱码了，但此处还需要再设置urlencode，转义下特殊符号
                $aPOST[] = $key."=".urlencode($val);
//                $aPOST[] = $key."=".$val;
            }
            $strPOST =  join("&", $aPOST);
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }


    public function test3(){
        $data['phones'] = 18664999020;
        $data['serial_no'] = 'SETFREE&amp;aaa)';
        $data['row_id'] = 'aaaaa';
        $query_param = $this->getQueryParamStr($data,'post');
//        header("Content-type: text/html; charset=utf-8");
//        echo '转义前：' . 'SETFREE&amp;aaa)' . '<br/>';
//        echo '转义后：' . urlencode('SETFREE&amp;aaa)') . '<br/>';
//        echo 'md5：' . md5('SETFREE&amp;aaa)');die;
        $result = $this->http_post_test(self::API_URL_PREFIX .'?method=getProjectInfo&',$query_param);
        header("Content-type: text/html; charset=utf-8");
        dump($result);die;
    }


}